﻿Imports System.Configuration
Imports System.Text.RegularExpressions

Public Class ItemLibrary
    Public Class DB_Item
#Region "Properties"
        Private _Name As String
        Public Property Name() As String
            Get
                Return _Name
            End Get
            Set(value As String)
                _Name = value
            End Set
        End Property
        Private _Parameters As List(Of String)
        Public Property Parameters() As List(Of String)
            Get
                Return _Parameters
            End Get
            Set(value As List(Of String))
                _Parameters = value
            End Set
        End Property
        Private _ID As Integer
        Public Property ID() As Integer
            Get
                Return _ID
            End Get
            Set(value As Integer)
                _ID = value
            End Set
        End Property
#End Region
        Public Function ParamList() As String
            Dim Returnstring As String = Parameters(0)
            For i As Integer = 1 To Parameters.Count - 1
                Returnstring = Returnstring & "⁞" & Parameters(i)
            Next
            Return Returnstring
        End Function
        Public Sub New(ByVal Name As String, ByVal Paramaters As List(Of String))
            _Name = Name
            _Parameters = Paramaters
        End Sub
    End Class

    Public Class ItemDB
#Region "Properties"
        Private _ConfigPath As String
        Private _Items As New HashSet(Of DB_Item)
        Public ReadOnly Property Items As HashSet(Of DB_Item)
            Get
                Return _Items
            End Get
            'Set(value As HashSet(Of DB_Item))
            '    _Items = value
            'End Set
        End Property
#End Region

#Region "Class Methods"
        Public Sub AddItem(ByVal Item As DB_Item)
            If SearchItem(Item.Name) IsNot Nothing Then
                Throw New Exception("Item with name '" & Item.Name & "' already exists!")
            Else
                Item.ID = Items.Count
                Items.Add(Item)
                SyncItem(Item)
            End If
        End Sub
        Public Sub LoadConfig(ByVal Filename As String)
            _ConfigPath = Filename
            If Filename.ToLower.StartsWith("ftp://") Then
                Console.WriteLine("Merging Database with Server....")
                If My.Computer.FileSystem.FileExists(My.Computer.FileSystem.CurrentDirectory & "\User_DB.cfg") = False Then
                    My.Computer.FileSystem.WriteAllText(My.Computer.FileSystem.CurrentDirectory & "\User_DB.cfg", "", False)
                End If
                Dim UserDB As String = FixLines(My.Computer.FileSystem.ReadAllText(My.Computer.FileSystem.CurrentDirectory & "\User_DB.cfg"))
                Dim Lines() As String = UserDB.Split(vbLf)
                For i As Integer = 0 To Lines.Count - 1

                    Dim Str As String = Lines(i)
                    Select Case Str.Split("│")(0)
                        Case "{ITEM}"
                            Dim Name As String = Str.Split("│")(1)
                            If UserDB.Contains("│" & Name & "│") = False Then
                                Console.WriteLine("Adding Item " & Name & " From Server_DB.cfg...")
                                Dim UserData As String = Str.Split("│")(2)
                                Dim SplitData() As String = UserData.Split("⁞")
                                Dim Params As New List(Of String)
                                For Int As Integer = 0 To SplitData.Count - 1
                                    Params.Add(SplitData(Int))
                                Next
                                Dim Item As New DB_Item(Name, Params)
                                Item.ID = Items.Count
                                Items.Add(Item)
                            End If
                    End Select
                Next
                LoadDB()
            Else
                If My.Computer.FileSystem.FileExists(_ConfigPath) Then
                    Dim UserDB As String = FixLines(My.Computer.FileSystem.ReadAllText(_ConfigPath))
                    Dim Lines() As String = UserDB.Split(vbLf)
                    For i As Integer = 0 To Lines.Count - 1
                        Dim Str As String = Lines(i)
                        Select Case Str.Split("│")(0)
                            Case "{ITEM}"
                                Dim Name As String = Str.Split("│")(1)
                                Dim UserData As String = Str.Split("│")(2)
                                Dim SplitData() As String = UserData.Split("⁞")
                                Dim Params As New List(Of String)
                                For Int As Integer = 0 To SplitData.Count - 1
                                    Params.Add(SplitData(Int))
                                Next
                                AddItem(New DB_Item(Name, Params))
                        End Select
                    Next
                Else
                    If _ConfigPath = Nothing Then
                        LoadConfig(My.Computer.FileSystem.CurrentDirectory & "\User_DB.cfg")
                    Else
                        My.Computer.FileSystem.WriteAllText(_ConfigPath, Nothing, False)
                    End If
                End If
            End If
        End Sub
        Public Sub SyncItem(ByVal Item_Sync As DB_Item)
            If _ConfigPath.ToLower.StartsWith("ftp://") Then

                Dim CFGPath As String = My.Computer.FileSystem.CurrentDirectory & "\User_DB.cfg"

                If My.Computer.FileSystem.FileExists(CFGPath) = False Then
                    My.Computer.FileSystem.WriteAllText(CFGPath, Nothing, False)
                End If

                My.Computer.Network.DownloadFile(_ConfigPath, CFGPath, Nothing, Nothing, False, 10000, True)

                Dim LocalDB As String = Regex.Replace(My.Computer.FileSystem.ReadAllText(CFGPath), "[\r\n]+\s*[\r\n]+", vbLf).Trim

                If LocalDB.Contains("│" & Item_Sync.Name & "│") = False Then
                    My.Computer.FileSystem.WriteAllText(CFGPath, vbLf & "{ITEM}│" & Item_Sync.Name & "│" & Item_Sync.ParamList, True)
                End If

                Console.WriteLine("Syncing...")

                My.Computer.Network.UploadFile(CFGPath, _ConfigPath)

            Else
                If _ConfigPath <> Nothing Then
                    My.Computer.FileSystem.WriteAllText(_ConfigPath, Nothing, False)
                    Dim First As Boolean = True
                    For Each Item As DB_Item In Items
                        If First = True Then
                            First = False
                            My.Computer.FileSystem.WriteAllText(_ConfigPath, "{ITEM}│" & Item.Name & "│" & Item.ParamList, True)
                        Else
                            My.Computer.FileSystem.WriteAllText(_ConfigPath, vbLf & "{ITEM}│" & Item.Name & "│" & Item.ParamList, True)
                        End If
                    Next
                End If
            End If
        End Sub
        Public Sub ReloadConfig()
            Items.Clear()
            LoadConfig(_ConfigPath)
        End Sub
        Public Sub LoadDB()
            If _ConfigPath.ToLower.StartsWith("ftp://") Then
                Console.WriteLine("Loading Server Database...")
                Dim CFGPath As String = My.Computer.FileSystem.CurrentDirectory & "\User_DB.cfg"
                Dim ServerPath As String = My.Computer.FileSystem.CurrentDirectory & "\Server_DB.cfg"

                If My.Computer.FileSystem.FileExists(CFGPath) = False Then
                    My.Computer.FileSystem.WriteAllText(CFGPath, Nothing, False)
                End If
                My.Computer.Network.DownloadFile(_ConfigPath, ServerPath, Nothing, Nothing, False, 10000, True)

                Dim ServerDB As String = Regex.Replace(My.Computer.FileSystem.ReadAllText(ServerPath), "[\r\n]+\s*[\r\n]+", vbLf).Trim
                Dim LocalDB As String = ""
                For Each Item As DB_Item In Items
                    LocalDB = LocalDB & vbLf & "{ITEM}│" & Item.Name & "│" & Item.ParamList
                    If ServerDB.Contains("│" & Item.Name & "│") = False Then
                        My.Computer.FileSystem.WriteAllText(CFGPath, vbNewLine & "{ITEM}│" & Item.Name & "│" & Item.ParamList, False)
                    End If
                Next

                LocalDB = Regex.Replace(LocalDB, "[\r\n]+\s*[\r\n]+", vbLf).Trim

                For i As Integer = 0 To ServerDB.Split(vbLf).Count - 1
                    Try
                        Dim Datastr As String = ServerDB.Split(vbLf)(i)
                        If Datastr <> Nothing Then
                            Dim Name As String = Datastr.Split("│")(1)
                            If LocalDB.Contains("│" & Name & "│") = False Then
                                Dim UserData As String = Datastr.Split("│")(2)
                                Dim SplitData() As String = UserData.Split("⁞")
                                Dim Params As New List(Of String)
                                For Int As Integer = 0 To SplitData.Count - 1
                                    Params.Add(SplitData(Int))
                                Next
                                Dim Item As New DB_Item(Name, Params)
                                Item.ID = Items.Count
                                Items.Add(Item)
                            End If
                        End If
                    Catch ex As Exception
                    End Try
                Next
                Console.WriteLine("Database Loaded!")
            Else
                If _ConfigPath <> Nothing Then
                    My.Computer.FileSystem.WriteAllText(_ConfigPath, Nothing, False)
                    Dim First As Boolean = True
                    For Each Item As DB_Item In Items
                        If First = True Then
                            First = False
                            My.Computer.FileSystem.WriteAllText(_ConfigPath, "{ITEM}│" & Item.Name & "│" & Item.ParamList, True)
                        Else
                            My.Computer.FileSystem.WriteAllText(_ConfigPath, vbLf & "{ITEM}│" & Item.Name & "│" & Item.ParamList, True)
                        End If
                    Next
                End If
            End If
        End Sub
        Public Sub MergeDB()
            If _ConfigPath.ToLower.StartsWith("ftp://") Then

                Dim CFGPath As String = My.Computer.FileSystem.CurrentDirectory & "\User_DB.cfg"
                Dim ServerPath As String = My.Computer.FileSystem.CurrentDirectory & "\Server_DB.cfg"

                If My.Computer.FileSystem.FileExists(CFGPath) = False Then
                    My.Computer.FileSystem.WriteAllText(CFGPath, Nothing, False)
                End If

                My.Computer.Network.DownloadFile(_ConfigPath, ServerPath, Nothing, Nothing, False, 10000, True)

                Dim ServerDB As String = Regex.Replace(My.Computer.FileSystem.ReadAllText(ServerPath), "[\r\n]+\s*[\r\n]+", vbLf).Trim
                Dim LocalDB As String = ""
                For Each Item As DB_Item In Items
                    LocalDB = LocalDB & vbLf & "{ITEM}│" & Item.Name & "│" & Item.ParamList
                    If ServerDB.Contains("│" & Item.Name & "│") = False Then

                        Dim Currenttext As String = My.Computer.FileSystem.ReadAllText(ServerPath) & vbNewLine & "{ITEM}│" & Item.Name & "│" & Item.ParamList

                        My.Computer.FileSystem.WriteAllText(CFGPath, Currenttext, False)

                    End If
                Next

                LocalDB = Regex.Replace(LocalDB, "[\r\n]+\s*[\r\n]+", vbLf).Trim

                For i As Integer = 0 To ServerDB.Split(vbLf).Count - 1
                    Try
                        Dim Datastr As String = ServerDB.Split(vbLf)(i)
                        If Datastr <> Nothing Then
                            Dim Name As String = Datastr.Split("│")(1)
                            If LocalDB.Contains("│" & Name & "│") = False Then
                                Dim UserData As String = Datastr.Split("│")(2)
                                Dim SplitData() As String = UserData.Split("⁞")
                                Dim Params As New List(Of String)
                                For Int As Integer = 0 To SplitData.Count - 1
                                    Params.Add(SplitData(Int))
                                Next
                                Dim Item As New DB_Item(Name, Params)
                                Item.ID = Items.Count
                                Items.Add(Item)
                            End If
                        End If
                    Catch ex As Exception
                    End Try
                Next

                Console.WriteLine("Merging Server Database with Client DB....")

                My.Computer.Network.UploadFile(CFGPath, _ConfigPath)

            Else
                If _ConfigPath <> Nothing Then
                    My.Computer.FileSystem.WriteAllText(_ConfigPath, Nothing, False)
                    Dim First As Boolean = True
                    For Each Item As DB_Item In Items
                        If First = True Then
                            First = False
                            My.Computer.FileSystem.WriteAllText(_ConfigPath, "{ITEM}│" & Item.Name & "│" & Item.ParamList, True)
                        Else
                            My.Computer.FileSystem.WriteAllText(_ConfigPath, vbLf & "{ITEM}│" & Item.Name & "│" & Item.ParamList, True)
                        End If
                    Next
                End If
            End If
        End Sub
#End Region
#Region "Class Functions"
        Private Function FixLines(ByVal Input As String)
            Return Regex.Replace(Input, "[\r\n]+\s*[\r\n]+", vbLf).Trim
        End Function
        Public Function DeleteItem(ByVal Name As String)
            Dim DeletedUsers As String = Nothing
            If _ConfigPath.ToLower.StartsWith("ftp://") Then
                Dim CFGPath As String = My.Computer.FileSystem.CurrentDirectory & "\User_DB.cfg"
                Dim TempPath As String = My.Computer.FileSystem.CurrentDirectory & "\Server_DB.Temp"

                My.Computer.Network.DownloadFile(_ConfigPath, TempPath, Nothing, Nothing, False, 100000, True)

                Dim ServerDB As String = My.Computer.FileSystem.ReadAllText(TempPath)
                Dim RemoveItems As New HashSet(Of DB_Item)

                For Each Item As DB_Item In Items
                    If Item.Name.ToLower = Name.ToLower Then
                        If DeletedUsers = Nothing Then
                            DeletedUsers = Item.Name
                        Else
                            DeletedUsers = DeletedUsers & ", " & Item.Name
                        End If
                        ServerDB = ServerDB.Replace("{ITEM}│" & Item.Name & "│" & Item.ParamList, Nothing)
                        RemoveItems.Add(Item)
                    End If
                Next
                For Each Item As DB_Item In RemoveItems
                    Items.Remove(Item)
                Next

                ServerDB = Regex.Replace(ServerDB, "[\r\n]+\s*[\r\n]+", vbLf).Trim

                My.Computer.FileSystem.WriteAllText(CFGPath, ServerDB, False)
                My.Computer.Network.UploadFile(CFGPath, _ConfigPath)
            Else
                Dim RemoveItems As New HashSet(Of DB_Item)
                For Each Item As DB_Item In Items
                    If Item.Name.ToLower = Name.ToLower Then
                        If DeletedUsers = Nothing Then
                            DeletedUsers = Item.Name
                        Else
                            DeletedUsers = DeletedUsers & ", " & Item.Name
                        End If
                        RemoveItems.Add(Item)
                    End If
                Next
                For Each Item As DB_Item In RemoveItems
                    Items.Remove(Item)
                Next
            End If
            MergeDB()
            If DeletedUsers <> Nothing Then
                Return "Item(s) " & DeletedUsers & " Have Been Deleted."
            Else
                Return "No Item(s) Have Been Deleted."
            End If
        End Function
        Public Function DeleteItemByID(ByVal ID As Integer)
            Dim DeletedUser As String = Nothing
            If _ConfigPath.ToLower.StartsWith("ftp://") Then
                Dim CFGPath As String = My.Computer.FileSystem.CurrentDirectory & "\User_DB.cfg"
                Dim TempPath As String = My.Computer.FileSystem.CurrentDirectory & "\Server_DB.Temp"

                My.Computer.Network.DownloadFile(_ConfigPath, TempPath, Nothing, Nothing, False, 100000, True)

                Dim ServerDB As String = My.Computer.FileSystem.ReadAllText(TempPath)

                Dim RemoveItems As New HashSet(Of DB_Item)
                For Each Item As DB_Item In Items
                    If Item.ID = ID Then
                        DeletedUser = Item.Name & " [" & ID & "]"
                        RemoveItems.Add(Item)
                        ServerDB = ServerDB.Replace("{ITEM}│" & Item.Name & "│" & Item.ParamList, Nothing)
                    End If
                Next
                For Each Item As DB_Item In RemoveItems
                    Items.Remove(Item)
                Next
                ServerDB = Regex.Replace(ServerDB, "[\r\n]+\s*[\r\n]+", vbLf).Trim
                My.Computer.FileSystem.WriteAllText(CFGPath, ServerDB, False)
                My.Computer.Network.UploadFile(CFGPath, _ConfigPath)

                If DeletedUser <> Nothing Then
                    Return "Item " & DeletedUser & " Has Been Deleted."
                Else
                    Return "Incorrect Item ID."
                End If

            Else
                Dim RemoveItems As New HashSet(Of DB_Item)
                For Each Item As DB_Item In Items
                    If Item.ID = ID Then
                        DeletedUser = Item.Name & " [" & ID & "]"
                        RemoveItems.Add(Item)
                    End If
                Next
                For Each Item As DB_Item In RemoveItems
                    Items.Remove(Item)
                Next
                MergeDB()
                If DeletedUser <> Nothing Then
                    Return "Item " & DeletedUser & " Has Been Deleted."
                Else
                    Return "Incorrect Item ID."
                End If
            End If
        End Function
        Public Function SearchItems(ByVal Name As String) As HashSet(Of DB_Item)
            Dim ReturnItems As New HashSet(Of DB_Item)
            For Each Item As DB_Item In Items
                If Item.Name.ToLower.Contains(Name.ToLower) Then
                    ReturnItems.Add(Item)
                End If
            Next
            Return ReturnItems
        End Function
        Public Function SearchItem(ByVal Name As String) As DB_Item
            For Each DBItem As DB_Item In Items
                If DBItem.Name.ToLower = Name.ToLower Then
                    Return DBItem
                End If
            Next
            Return Nothing
        End Function
#End Region

        Public Sub New(Optional ConfigPath As String = Nothing)
            LoadConfig(ConfigPath)
        End Sub
    End Class
End Class
